<?php
include_once(MAIN_PATH.'config/global_vars.php');
  class search_controller_search extends Base
  {
      private $sModel;
      private $mainQuery;
      const DOTPAY_PIN = "0123456789012345";
      const DOTPAY_CONTROL = "abcdefghj";
      const DOTPAY_SERVICE = "";
      const DOTPAY_CODE = "";
      const DOTPAY_USERNAME = "";
      const DOTPAY_PASSWORD = "";
      const DOTPAY_ID = "53558";
      const DOTPAY_STATUS_OK = 'OK';
      const DOTPAY_STATUS_FAIL = 'FAIL';
      const DOTPAY_GO_BACK_TO_SOSJOB_BUTTON_TXT = "Powrót do serwisu SOSJOB";
      private $DOTPAY_URL;
      private $DOTPAY_URLC;
      public $common;
      
      public function __construct()
      {
          $this -> sModel = new searchQuery();
          $this -> mainQuery = new mainQuery();
          $this->DOTPAY_URL = SITE_ADDRESS ."platnosc-zakonczona";
          $this->DOTPAY_URLC = SITE_ADDRESS ."platnosc-podsumowanie";
          parent::__construct();
          $this->view->assign('site_address', SITE_ADDRESS);
      }
      /**
       * Get params from dotpay server
       * Na ta akcje wyslany jest POST przez DOTPAY ze statusem platnosci
       */
      public function getpay(){
          $params = array_merge($_POST, $_GET);
          $ip = trim($_SERVER['REMOTE_ADDR']);
          //print_r($params);
          if($ip == "195.150.9.37" || $ip =="217.17.41.5"){
              $code = self::DOTPAY_PIN.":".self::DOTPAY_ID.":".self::DOTPAY_CONTROL;
              $code .= ":".$params['t_id'].":".$params['amount'].":".$params['email'];
              $code .= ":".self::DOTPAY_SERVICE.":".self::DOTPAY_CODE;
              $code .= ":".self::DOTPAY_USERNAME.":".self::DOTPAY_PASSWORD;
              $code .= ":".$params['t_status'];
              $md5Code = md5($code);

              $t_status = trim($params['t_status']);//aktualny stan transkacji
              if($md5Code == $params['md5']){
                  if($params['status'] == "OK"){
                      //save it to databse
                      $payModel = new payQuery();
                      $payModel->add($params);
                      echo self::DOTPAY_STATUS_OK;
                      exit;
                  }
              }
          }
          echo self::DOTPAY_STATUS_FAIL;
          exit;
      }
      /**
       * Show message after dotpay action is finished
       * Na ta akcje nastpuje przkierowanie uzytkownika gdy nacisnienie przycisk powrot do serwisu, wygenerowany przez dotpy
       */
      public function finishpay(){
          $params = array_merge($_POST, $_GET);
          echo 'zakonczona transakcja';
          echo '<pre>';
          print_r($params);
          exit;
      }
      
      public function searchPerson()
      {
            if(isset($_SESSION[PREFIX]['user']['id']) && $_SESSION[PREFIX]['user']['id'] != "")
            {
                $userData = $this -> sModel -> getUserData($_SESSION[PREFIX]['user']['id']);
                $this -> view -> assign('userData', $userData);
            }
            $this -> view -> assign('showCart', 'show');
            $map = new GoogleMapAPI('map');
            $map -> setAPIKey('ABQIAAAAHy-4chTxWi7fRAXj5xfkGRTVeRltro6I6Asm8fjVGF4U7FNUOBQyKduIHYGVXdJcpJrs6BUDWFe7Wg');
            $temp1 = array();
            $temp1['lat'] = '52.227652';
            $temp1['lon'] = '21.009303';
            if(isset($_POST['address']) && $_POST['address'] != "")
            {
                $temp1 = $map -> geoGetCoords($_POST['address']);
                if($temp1 === false)
                {
                    $temp1 = array();
                    $temp1['lat'] = '52.227652';
                    $temp1['lon'] = '21.009303';    
                }
                if(isset($_POST['lookingPerson']) && $_POST['lookingPerson'] != '')
                {
                    $persons = $this -> sModel -> getPersonFromCategory($_POST);
                    $searchedWorkers = array();
                    $markerOrder = 1;
                    foreach($persons as $key => $value)
                    {
                        $value['markerOrder'] = $key + 1;
                        $value['company_name'] = trim($value['company_name']);
                        $dis = $map -> geoGetDistance($temp1['lat'], $temp1['lon'], $value['lat'], $value['lon'], 'K');
                        if($dis <= $value['distance'])
                        {
                            $value['markerOrder'] = $markerOrder;
                            array_push($searchedWorkers, $value);
                            ++$markerOrder;
                        }
                    }
                    $arr = array();
                    $marge = array();
                    $this -> view -> assign('countOfAll', count($searchedWorkers)); 
                    foreach($searchedWorkers as $key=>$value)
                    {
                        if($key%15 != 0)
                        {
                            array_push($arr, $value);   
                        }   
                        else
                        {
                            if($key != 0)
                            {
                                array_push($marge, $arr);
                                $arr = array();
                                array_push($arr, $value);       
                            }
                            else
                            {
                                array_push($arr, $value);            
                            }
                        }
                        
                        if($key+1 == count($searchedWorkers) && $key%15 != 0)
                        {
                            array_push($marge, $arr);    
                        } 
                    }
                    $pages = ceil(count($searchedWorkers)/15);
                    $this -> view -> assign('marge', $marge);
                    $this -> view -> assign('pages', $pages);
                    $this -> view -> assign('workers', $searchedWorkers);
                    $common = new CommonQuery;
                    $res = $this -> sModel -> getUsersWithPhone(); 
                    $this -> view -> assign('searchPearson', $res);
                }
                else
                {
                    $temp1 = array();
                    $temp1['lat'] = '52.227652';
                    $temp1['lon'] = '21.009303';
                }    
            }
            else
            {
                $temp1 = array();
                $temp1['lat'] = '52.227652';
                $temp1['lon'] = '21.009303';      
            }
            $prof = $this -> mainQuery -> getAllProf();
            $str = "";
            foreach($prof as $key => $value)
            {
                $str .= $value['name'].',';    
            }
            $this -> view -> assign('autoData', $str);
            $this -> view -> assign('pLat', $temp1['lat']);
            $this -> view -> assign('pLon', $temp1['lon']);
            $this -> view -> assign('reason', 'search');
            if(isset($_POST['lookingPerson']))
            {
                $this -> view -> assign('lookingPerson', $_POST['lookingPerson']);    
            }
            else
            {
                $this -> view -> assign('lookingPerson', 'Kogo szukasz ?');     
            } 
            if(isset($_POST['address']))
            {
                $this -> view -> assign('address', $_POST['address']);   
            }
            else
            {
                $this -> view -> assign('address', 'Gdzie szukasz ?');    
            }
            $this->view->assign('finishedActionUrl', $this->DOTPAY_URL);
            $this->view->assign('urlc', $this->DOTPAY_URLC); 
            $this->view->assign('id', self::DOTPAY_ID);
            $this->view->assign('control', self::DOTPAY_CONTROL);
            $this->view->assign('button_text', self::DOTPAY_GO_BACK_TO_SOSJOB_BUTTON_TXT);
            $this->view->assign('post', isset($_POST)? $_POST: array());

      }
      
      public function searchMain()
      {
          
      }
      
      public function sendSms()
      {
//        pre($_POST);
        $smsApi = new smsApi();
        $common = new CommonQuery();
        
        $senderPhone = $_POST['phone'];
        if(isset($_SESSION[PREFIX]['user']['id']) && $_SESSION[PREFIX]['user']['id'] != "")
        {
            $senderData = $this -> sModel -> getUserData($_SESSION[PREFIX]['user']['id']);
            $senderPhone = $senderData[0]['phone'];
        }
        
        $smsText = 'SOSpraca: Zlecę pracę dla '.$_POST['lookingPerson'].' w miejscu '.$_POST['address'].' '.$_POST["when"].'. Mój numer to: '.$senderPhone.'.';
        
        $interval = 0;
        switch($_POST['when'])
        {
            case 'na jutro':
            {
                $interval = 3600*24; 
                break;
            }
            case 'za 2 dni':
            {
                $interval = 3600*48;
                break;
            }
            case 'za 3 dni':
            {
                $interval = 3600*72;
                break;
            }
            case 'za tydzień':
            {
                $interval = 3600*24*7;
                break;
            }
        }
        
        $data = time() + $interval; 
        $el = array();
        $catId = $this -> sModel -> getCategoryFromName(strtolower($_POST['lookingPerson']));
        $el['category_id'] = $catId;
        $el['end_date'] = date('Y-m-d', $data).' 23:59:59';
        $el['where_work'] = $_POST['address'];
        $el['description'] = $smsText;
        $el['when_work'] = $_POST['when'];
        $el['who_work'] = $_POST['lookingPerson'];
        $el['ip'] = $ip=$_SERVER['REMOTE_ADDR'];
        $common -> save($el, 'offers');
        
        $lastId = $this -> sModel -> getLastOfferId();
        
        
        
        foreach($_POST['ids'] as $key => $value)
        {
            $userData = $this -> sModel -> getUserDataFromService($value);
//            pre($userData);
//            pre('SOSpraca: Zlecę pracę dla '.$_POST['lookingPerson'].' w miejscu '.$_POST['address'].' '.$_POST["when"].'. Mój numer to: '.$senderPhone.'.', $userData[0]['phone']);
            $res = $smsApi -> sendSingleSms('SOSpraca: Zlecę pracę dla '.$_POST['lookingPerson'].' w miejscu '.$_POST['address'].' '.$_POST["when"].'. Mój numer to: '.$senderPhone.'.', $userData[0]['phone']);
//            pre($res);
            $res[0] = "OK";  
            if($res[0] == "OK")
            {
                if(isset($_SESSION[PREFIX]['user']['id']))
                {
                    $this -> sModel -> decreseSms($_SESSION[PREFIX]['user']['id']);   
                }
                $el = array();
                if(isset($_SESSION[PREFIX]['user']['id']) && $_SESSION[PREFIX]['user']['id'] != "")
                {
                    $el['sender_id'] = $_SESSION[PREFIX]['user']['id'];    
                }
                else
                {
                    $el['flag_anonimus'] = 'true';    
                }
                
                $el['reciever_id'] = $value;
                $el['content'] = $res[1];
                $el['status'] = $res[2];   
                $common -> save($el, 'sms');
                                                                         
                $el = array();
                $el['act_id'] = $lastId;
                $el['activity_kind'] = 2;
                $el['user_id'] = $userData[0]['id'];
                $this -> common -> save($el, 'activities');
            }   
        }
        
        
        $message = array();
        $message['content'] = "SMS-y zostały rozesłane do wybranych osób";
        $message['type'] = "success";
        $this -> setMessage($message);
        $this -> FriendlyLink(SITE_ADDRESS); 
      }
  }
?>
